﻿using WebService.ExtendedMethods;
using Yitter.IdGenerator;
using Microsoft.EntityFrameworkCore;

namespace WebService.EF.Tables
{
    public partial class WeighingDataCache
    {
        public async Task<int> SaveAsync(DbService db)
        {
            var ticketCode = TicketCode;
            var carPlateNum = CarPlateNumber;

            await db.WeighingDataCaches.Where(p => DateTime.Now > p.ExpireDate).ExecuteDeleteAsync();

            var data = db.WeighingDataCaches
                .IfWhere(() => !string.IsNullOrWhiteSpace(ticketCode), p => p.TicketCode == ticketCode)
                .IfWhere(() => !string.IsNullOrWhiteSpace(carPlateNum), p => p.CarPlateNumber == carPlateNum).OrderByDescending(p => p.CreateDate).FirstOrDefault();

            if (ExpireDate == null)
            {
                ExpireDate = DateTime.Now.AddMinutes(30);
            }

            if (data == null)
            {
                Id = YitIdHelper.NextId();
                UpdateDate = CreateDate = DateTime.Now;
                db.WeighingDataCaches.Add(this);
            }
            else
            {
                data.TicketCode = ticketCode;
                data.CarPlateNumber = carPlateNum;
                data.GoodsCode = GoodsCode;
                data.GoodsName = GoodsName;
                data.GoodsWeight = GoodsWeight;
                data.GoodsType = GoodsType;
                data.FreightUnit = FreightUnit;
                data.Sender = Sender;
                data.Receiver = Receiver;
                data.Reserve1 = Reserve1;
                data.Reserve2 = Reserve2;
                data.Reserve3 = Reserve3;
                data.Reserve4 = Reserve4;
                data.ExpireDate = ExpireDate;
                data.UpdateDate = DateTime.Now;
                db.Entry(data).State = EntityState.Modified;
            }

            var count = await db.SaveChangesAsync();

            return count;
        }
    }
}
